<template>
    <view class="container">
        <swiper
            id="video-swiper"
            class="video-swiper"
            :circular="circular"
            :easing-function="easingFunction"
            vertical
            :current="swiperCurrent"
            @change="changePlay"
            :duration="duration"
            @animationfinish="animationfinish"
        >
            <!-- curQueue 循环会导致video重新插入，objectFit 不可变更 -->
            <swiper-item v-for="(item, index) in curQueue" :key="index">
                <video
                    :id="'video_' + index"
                    class="video"
                    :loop="loop"
                    enable-play-gesture
                    enable-progress-gesture
                    :show-center-play-btn="false"
                    :controls="false"
                    :src="item.url"
                    :data-id="item.id"
                    :data-myindex="item.myindex"
                    :autoplay="false"
                    :object-fit="item.objectFit || 'cover'"
                    :data-index="index"
                    :data-allow="item.allowPlay"
                    :enable-play-gesture="false"
                    @play="onPlay"
                    @pause="onPause"
                    @ended="onEnded"
                    @error="onError"
                    @timeupdate="onTimeUpdate"
                    @waiting="onWaiting"
                    @progress="onProgress"
                    @loadedmetadata="onLoadedMetaData"
                    @tap="clickVideo"
                ></video>

                <!-- <image class="img"
        wx:if="{{!videoBol[index]}}"
        data-index="{{index}}"
        data-id="{{item.id}}" 
        data-allow="{{item.allowPlay}}"
        bind:tap="clickVideo" 
        src="../../images/home-play.png"></image> -->

                <!-- <view class="color-view" >video_{{item.idxKey}}</view> -->
            </swiper-item>
        </swiper>
    </view>
</template>

<script>
export default {
    data() {
        return {
            swiperObj: null,
            nextQueue: [],
            prevQueue: [],
            curQueue: [],
            circular: false,
            last_var: 1,
            change_var: -1,
            invalidUp_var: 0,
            invalidDown_var: 0,
            videoContexts_var: [],
            total: 0,
            activeId: null,
            playcurrentindex: 0,
            videoPlaying: true,

            // 标记视频是否正在播放
            videoBol: [false, false, false, false],

            swiperCurrent: '',
            pop_var: ''
        };
    },
    options: {
        addGlobalClass: true,
        pureDataPattern: /^_/
    },
    props: {
        duration: {
            type: Number,
            default: 500
        },
        easingFunction: {
            type: String,
            default: 'default'
        },
        loop: {
            type: Boolean,
            default: false
        },
        allowplay: {
            type: Boolean,
            default: false
        },
        index: {
            type: Number,
            default: 0
        },
        videoList: {
            type: Array,
            default: () => []
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
    },
    methods: {
        attached: function attached() {
            this._videoContexts = [
                uni.createVideoContext('video_0', this),
                uni.createVideoContext('video_1', this),
                uni.createVideoContext('video_2', this),
                uni.createVideoContext('video_3', this)
            ];
        },

        setplay() {
            console.log('到这里了setplay');
            // var newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
            if (this.videoList.length) {
                console.log(9999);
                this.videoList.map((item, index) => {
                    return (item.idxKey = index + 1);
                });
                if (this.videoList.length <= 300) {
                    console.log(888);
                    this.videoListChangedFun(this.videoList);
                } else {
                    // 防止当前数组被污染
                    let arr = JSON.parse(JSON.stringify(this.videoList));
                    // 去掉已有的数据
                    let nextArr = arr.splice(this.total);
                    this.nextQueue.push(...nextArr);
                }
                this.setData({
                    total: this.videoList.length
                });
            }
        },

        videoListChangedFun: function _videoListChanged(newVal) {
            var that = this;
            var index = this.index;
            var total = newVal.length;
            // 如果传入的index大于总数，则默认从0开始播放
            if (index + 1 > total) {
                index = 0;
            }
            var data = this;
            let remainder = index % 3; // 3的余数--当前轮播位置
            var curQueue = [];
            var _pop = [];
            var swiperCurrent = remainder;
            newVal.forEach(function (item, idx) {
                item.index = idx;
                data.nextQueue.push(item);
            });
            // console.log(newVal, 'newval', data);
            if (data.curQueue.length === 0) {
                let curIndex = index > 0 ? index - 1 : 0;
                that._change = ((index % 3) + 1) % 3;
                // 假设直接从顶部滑下来
                // _this.data._last = index === 0 ? 0 : // 如果初始播放第0个视频
                //     // index不是0，刚好是3的倍数，上一个swiper-item的索引是2(最后一个)
                //     _this.data._change === 0 ? 2 : _this.data._change - 1;// 其他情况直接用_change - 1就行
                that._last = remainder;
                that._invalidDown = index === 0 ? 1 : 0; // 如果刚好是第0个，不允许下滑

                that._invalidUp = total - curIndex < 2 ? 1 : 0; // 这个比较复杂了

                // 设置前后还剩多少数据
                that.prevQueue = newVal.slice(0, curIndex);
                that.nextQueue = newVal.slice(curIndex + 3);
                var circular = true;
                if (that.nextQueue.length === 0 && that._change !== 0) {
                    circular = false;
                }
                if (that.prevQueue.length === 0 && that._change !== 2) {
                    circular = false;
                }

                // 当前swiper展示的数组顺序
                let indexAdd = index + 1;
                let indexAdd2 = index + 2;
                let indexSub = index - 1;
                if (total > 4 && total % 3 == 1 && total - 1 - index <= 2) {
                    // 除以3余1

                    curQueue = [...newVal.slice(total - 1, total), ...newVal.slice(total - 3, total - 2), ...newVal.slice(total - 2, total - 1), ...newVal.slice(total - 1, total)];
                    that.circular = circular = false;
                    if (total - 1 - index == 0) {
                        that._change = 0;
                        that._invalidDown = 0;
                        that._invalidUp = 1;
                        that._last = 3;
                        swiperCurrent = 3;
                        that.prevQueue = newVal.slice(0, curIndex - 1);
                    } else if (total - 1 - index == 1) {
                        that._change = 0;
                        that._invalidDown = 0;
                        that._invalidUp = 0;
                        that._last = 2;
                    } else if (total - 1 - index == 2) {
                        that._change = 2;
                        that._invalidDown = 0;
                        that._invalidUp = 0;
                        that._last = 1;
                        that.circular = circular = true;
                        curQueue = [...newVal.slice(indexSub, index), ...newVal.slice(index, indexAdd), ...newVal.slice(indexAdd, indexAdd2)];
                    }
                } else if (total > 4 && total % 3 == 2 && total - index - 1 <= 1) {
                    // 除以3余2

                    _pop = newVal.slice(total - 3, total - 2);
                    _pop = _pop[0];
                    if (total - index - 1 == 0 || total == index + 2) {
                        if (total == index + 2) {
                            // 当直接定位到倒数第二个播放
                            that._change = 1;
                            that._invalidDown = 0;
                            that._invalidUp = 0;
                            that._last = 0;
                            circular = false;
                            curQueue = [
                                ...newVal.slice(total - 2, total - 1),
                                ...newVal.slice(total - 1, total)
                                // ...newVal.slice(total - 3, total - 2),
                            ];
                        } else {
                            that._change = 1;
                            that._invalidDown = 0;
                            that._invalidUp = 1;
                            that._last = 1;
                            circular = false;
                            curQueue = [...newVal.slice(total - 2, total - 1), ...newVal.slice(total - 1, total)];
                        }
                        that.prevQueue = newVal.slice(0, total - 3);
                    } else if (total - index - 1 == 1) {
                        that._change = 1;
                        that._invalidDown = 0;
                        that._invalidUp = 0;
                        that._last = 0;
                        circular = true;
                        curQueue = [...newVal.slice(total - 2, total - 1), ...newVal.slice(total - 1, total), ...newVal.slice(total - 3, total - 2)];
                    }
                } else {
                    if (total <= 4) {
                        // 当从第一个视频播放不需要其他操作
                        // 当轮播第一次 初始化值
                        that._change = -1;
                        that._last = 1;
                        that._invalidDown = 0;
                        that._invalidUp = 0;
                        // curQueue = newVal.slice(curIndex, curIndex + 3);
                        curQueue = newVal;
                        circular = false;
                    } else {
                        if (remainder == 0 && total > 4) {
                            let lastArr = newVal.slice(indexSub, index); // 当这是第N轮的第一个swiper，需要裁剪上一个尾的数据
                            if (index == 0) {
                                // 当这是第一个swiper位置视频，当前最后一个视频为下2个
                                that._change = -1;
                                that._last = 1;
                                that._invalidDown = 0;
                                that._invalidUp = 0;
                                lastArr = newVal.slice(indexAdd2, indexAdd2 + 1);
                            }
                            curQueue = [...newVal.slice(index, indexAdd), ...newVal.slice(indexAdd, indexAdd2), ...lastArr];
                        } else if (remainder == 1 && total > 4) {
                            curQueue = [...newVal.slice(indexSub, index), ...newVal.slice(index, indexAdd), ...newVal.slice(indexAdd, indexAdd2)];
                        } else if (remainder == 2 && total > 4) {
                            let homeArr = newVal.slice(indexAdd, indexAdd2); // 当这是第三个swiper，需要裁剪将来一个
                            if (total === index + 1) {
                                // 当这是最后一个视频时，只需要裁剪前2个
                                circular = false;
                                homeArr = newVal.slice(index - 2, indexSub);
                            }
                            curQueue = [...homeArr, ...newVal.slice(indexSub, index), ...newVal.slice(index, indexAdd)];
                        }
                    }
                }
                if (total <= 4) {
                    swiperCurrent = index;
                }
                this.setData(
                    {
                        curQueue: curQueue,
                        total,
                        circular,
                        swiperCurrent,
                        pop_var: _pop
                    },
                    function () {
                        console.log(7777);
                        console.log(this.curQueue[this.swiperCurrent]);
                        let allow = this.curQueue[this.swiperCurrent].allowPlay;
                        that.playCurrent(swiperCurrent, allow);
                        obj = that.zpSelectComponent('#video-swiper');
                    }
                );
            }
        },

        animationfinish: function animationfinish(e) {
            // console.log(e);
            var _data = this;
            var _last = _data._last;
            var _change = _data._change;
            var curQueue = _data.curQueue;
            var prevQueue = _data.prevQueue;
            var nextQueue = _data.nextQueue;
            var total = _data.total;
            var current = e.detail.current;
            // console.log(curQueue[current]);
            // console.log(555555555);
            var diff = current - _last;
            this.swiperCurrent = current;
            this.setData({
                playcurrentindex: current
            });
            this.$emit('getplayid', {
                detail: {
                    myindex: curQueue[current].myindex
                }
            });
            this.playCurrent(current, curQueue[current].allowPlay);

            // 判断总数据是否大于等于10，并且下滑剩下4个视频开始请求接口拿数据；这里大小可以根据自己需求修改
            if (total >= 10 && nextQueue.length < 5) {
                this.$emit('UpdataVideo', {
                    detail: {}
                });
            }
            if (diff === 0 || total <= 4) {
                return;
            }
            this._last = current;
            this.$emit('change', {
                detail: {
                    activeId: curQueue[current].chapnum
                }
            });
            var direction = diff === 1 || diff === -2 ? 'up' : 'down';
            if (direction === 'up') {
                if (this._invalidDown === 0) {
                    var change = (_change + 1) % 3;
                    var add = nextQueue.shift();
                    var remove = curQueue[change];
                    if (add) {
                        prevQueue.push(remove);
                        curQueue[change] = add;
                        this._change = change;

                        // strart 判断是否总数余数为多少，裁剪当前轮播放2个还是4个。正常显示3个轮播
                        if (total % 3 === 1 && nextQueue.length === 0) {
                            let timers = new Date();
                            let addItem = JSON.parse(JSON.stringify(add));
                            addItem.idxKey = timers.getTime();
                            curQueue[3] = addItem;
                        } else if (total % 3 === 2 && nextQueue.length === 0) {
                            let _pop = curQueue.pop();
                            this.setData({
                                pop_var: _pop
                            });
                        }
                        // end
                    } else {
                        this._invalidUp += 1;
                    }
                } else {
                    this._invalidDown -= 1;
                }
            }
            if (direction === 'down') {
                if (this._invalidUp === 0) {
                    var _change2 = _change;
                    var _remove = curQueue[_change2];
                    var _add = prevQueue.pop();
                    if (_add) {
                        curQueue[_change2] = _add;
                        nextQueue.unshift(_remove);
                        this._change = (_change2 - 1 + 3) % 3;
                    } else {
                        this._invalidDown += 1;
                    }
                } else {
                    // strart 判断是否总数余数为多少，裁剪当前轮播放2个还是4个。正常显示3个轮播
                    if (total % 3 === 1 && curQueue.length === 4) {
                        curQueue.pop();
                    } else if (total % 3 === 2 && nextQueue.length === 0) {
                        curQueue.push(this._pop);
                    }
                    // end

                    this._invalidUp -= 1;
                }
            }
            var circular = true;
            if (nextQueue.length === 0 && current !== 0) {
                circular = false;
            }
            if (prevQueue.length === 0 && current !== 2) {
                circular = false;
            }
            this.setData(
                {
                    curQueue: curQueue,
                    circular: circular
                },
                () => {
                    // console.log('curQueue:', JSON.parse(JSON.stringify(this.data.curQueue)), 'nextQueue:', this.data.nextQueue, 'prevQueue:', this.data.prevQueue)
                    // console.log(this.data);
                    // console.log(curQueue[current], 'id', this.data, current);
                    // console.log('_change:', this.data._change, '_invalidDown:', this.data._invalidDown, '_invalidUp:', this.data._invalidUp, '_last:', this.data._last)
                }
            );
        },

        autoNext() {
            let cur = this.swiperCurrent + 1;
            if (cur >= 3) {
                cur = 0;
            }
            this.setData({
                swiperCurrent: cur
            });
            // obj.swipeNext()

            // var swiper = this.selectComponent('.video-swiper');
            // query.swiperNext();
        },

        gotoTime(curTime, duration) {
            //拖动播放
            this._videoContexts[this.playcurrentindex].seek((curTime / 100) * duration); //完成拖动后，计算对应时间并跳转到指定位置
            // this.data._videoContexts[this.data.playcurrentindex].play()
            setTimeout(() => {
                for (let item of this._videoContexts) {
                    item.pause();
                }
                this._videoContexts[this.playcurrentindex].play();
                this.setData({
                    videoPlaying: true
                });
                this.$emit('getplaying', {
                    detail: {
                        val: this.videoPlaying
                    }
                });
            }, 100);
        },

        stopvideo() {
            for (let item of this._videoContexts) {
                item.pause();
            }
            this._videoContexts[this.playcurrentindex].pause();
            this.setData({
                videoPlaying: false
            });
            this.$emit('getplaying', {
                detail: {
                    val: this.videoPlaying
                }
            });
        },

        // 点击播放或暂停
        playvideo() {
            console.log('进来了');
            console.log(this._videoContexts);
            console.log(this.playcurrentindex);
            console.log(this.videoPlaying);
            if (!this.videoPlaying) {
                let allow = this.curQueue[this.playcurrentindex].allowPlay;
                if (allow) {
                    setTimeout(() => {
                        for (let item of this._videoContexts) {
                            item.pause();
                        }
                        this._videoContexts[this.playcurrentindex].play();
                        this.setData({
                            videoPlaying: true
                        });
                        this.$emit('getplaying', {
                            detail: {
                                val: this.videoPlaying
                            }
                        });
                    }, 300);
                }
            } else {
                for (let item of this._videoContexts) {
                    item.pause();
                }
                this._videoContexts[this.playcurrentindex].pause();
                this.setData({
                    videoPlaying: false
                });
                this.$emit('getplaying', {
                    detail: {
                        val: this.videoPlaying
                    }
                });
            }
        },

        clickVideo(e) {
            this.$emit('getid', {
                detail: {
                    myindex: e.target.dataset.myindex
                }
            });
            return;
            let _this = this;
            let current = this.swiperCurrent;
            let index = e.currentTarget.dataset.index;
            let allow = e.target.dataset.allow;
            var videoContextPrev = uni.createVideoContext(`video_${current}`, this);
            if (this.videoBol[index]) {
                // console.log(index);
                console.log(allow);
                videoContextPrev.pause();
                this.setData({
                    videoPlaying: false
                });
            } else {
                videoContextPrev.pause();
                this.setData({
                    videoPlaying: false
                });
                setTimeout(function () {
                    //将点击视频进行播放
                    // console.log(111111111);
                    // console.log(_this.properties.allowplay);
                    console.log(allow);
                    if (allow) {
                        videoContextPrev.play();
                        this.setData({
                            videoPlaying: true
                        });
                    }
                }, 300);
            }
        },

        playCurrent: function playCurrent(current, allow) {
            this.setData(
                {
                    swiperCurrent: current
                },
                () => {
                    let _videoContexts = this._videoContexts;
                    console.log(_videoContexts);
                    _videoContexts.map((item, index) => {
                        if (current == index) {
                            if (allow) {
                                console.log(index);
                                console.log(66666);
                                for (let sitem of this._videoContexts) {
                                    sitem.stop();
                                }
                                item.play();
                                this.setData({
                                    videoPlaying: true
                                });
                                this.$emit('getplaying', {
                                    detail: {
                                        val: this.videoPlaying
                                    }
                                });
                                this.$emit('setread', {
                                    detail: {}
                                });
                            }
                        } else {
                            item.stop();
                        }
                    });
                }
            );
        },

        onPlay: function onPlay(e) {
            this.trigger(e, 'play');
            let index = e.currentTarget.dataset.index;
            let id = e.currentTarget.dataset.chapnum;
            let allow = e.currentTarget.dataset.allow;
            if (allow) {
                this.setData({
                    [`videoBol[${index}]`]: true
                });
            }
        },

        changePlay: function changePlay(e) {
            this.trigger(e, 'change');
        },

        onPause: function onPause(e) {
            this.trigger(e, 'pause');
            let index = e.currentTarget.dataset.index;
            this.setData({
                [`videoBol[${index}]`]: false
            });
        },

        onEnded: function onEnded(e) {
            this.trigger(e, 'ended');
            let index = e.currentTarget.dataset.index;
            this.setData({
                [`videoBol[${index}]`]: false
            });
        },

        onError: function onError(e) {
            this.trigger(e, 'error');
            let index = e.currentTarget.dataset.index;
            this.setData({
                [`videoBol[${index}]`]: false
            });
        },

        onTimeUpdate: function onTimeUpdate(e) {
            // console.log(e);
            // this.trigger(e, 'timeupdate');
            this.$emit('timeupdate', {
                detail: {
                    currentTime: e.detail.currentTime,
                    duration: e.detail.duration,
                    myindex: e.target.dataset.myindex
                }
            });
        },

        onWaiting: function onWaiting(e) {
            this.trigger(e, 'wait');
        },

        onProgress: function onProgress(e) {
            this.trigger(e, 'progress');
        },

        onLoadedMetaData: function onLoadedMetaData(e) {
            this.trigger(e, 'loadedmetadata');
        },

        trigger: function trigger(e, type) {
            var ext = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
            var detail = e.detail;
            var activeId = e.target.dataset.id;
            this.$emit(type, {
                detail: Object.assign(
                    Object.assign(Object.assign({}, detail), {
                        activeId: activeId
                    }),
                    ext
                )
            });
            this.setData({
                activeId: activeId
            });
        }
    },
    created: function () {},
    watch: {
        videoList: {
            handler: function observer() {
                var newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
                // console.log(newVal);
                // console.log(868686);
                if (newVal.length) {
                    newVal.map((item, index) => {
                        return (item.idxKey = index + 1);
                    });
                    if (newVal.length <= 300) {
                        this.videoListChangedFun(newVal);
                    } else {
                        // 防止当前数组被污染
                        let arr = JSON.parse(JSON.stringify(newVal));
                        // 去掉已有的数据
                        let nextArr = arr.splice(this.total);
                        this.nextQueue.push(...nextArr);
                    }
                    this.setData({
                        total: newVal.length
                    });
                }
            },

            immediate: true,
            deep: true
        }
    }
};

/***/
</script>
<style>
.container {
    width: 100%;
    height: 100%;
}
.video-swiper {
    width: 100%;
    height: 100%;
}
.video_item {
    height: 100%;
    width: 100%;
}
.video {
    width: 100vw;
    height: 100vh;
}
.img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 82rpx;
    height: 84rpx;
    margin: auto;
    z-index: 5;
}
.color-view {
    position: fixed;
    left: 0;
    top: 0;
    color: aqua;
}
</style>
